package com.thread.pool.application.scanner.pool;

import com.thread.pool.application.scanner.factory.NamedThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Ldanniel
 */
@Configuration
public class ThreadPoolConfig   {
    public static final String prefix = "concurrent-thread-pool-";
    @Bean("getThreadPool")
    public ThreadPoolTaskExecutor getThreadPool(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取到服务器的cpu内核
        int i = Runtime.getRuntime().availableProcessors();
        //核心池大小
        executor.setCorePoolSize(10);
        //最大线程数
        executor.setMaxPoolSize(100);
        //队列程度
        executor.setQueueCapacity(1000);
        //线程空闲时间
        executor.setKeepAliveSeconds(1000);
        //线程前缀名称
        executor.setThreadNamePrefix(prefix);
        //配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;

    }

//    public   ThreadPoolExecutor getThreadPoolExecutor(){
//         ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
//                //线程池大小
//                3,
//                //线程池最大数量
//                10,
//                //超出 corePoolSize 后创建的线程存活时间或者是所有线程最大存活时间，取决于配置。
//                10L,
//                //keepAliveTime 的时间单位
//                TimeUnit.SECONDS,
//                //任务队列，是一个阻塞队列，当线程数已达到核心线程数，会将任务存储在阻塞队列中。100-队列数量
//                new LinkedBlockingQueue(100),
//                //线程名称
//                // TODO: 2022/11/6 增加线程工厂
//                new NamedThreadFactory(prefix),
//                //拒绝策略；当队列已满并且线程数量达到最大线程数量时，会调用该方法处理该任务。
//                new ThreadPoolExecutor.CallerRunsPolicy());
//         return threadPoolExecutor;
//    }
}
